<template>
  <div class="mac-launchpad-layout">
    <!-- 顶部栏 -->
    <header class="header">
      <div class="header-left">
        <img src="@/assets/logo.png" alt="Logo" class="logo" />
        <span class="app-name">Big ERP - Mac Launchpad</span>
      </div>
      <div class="header-right">
        <el-tooltip content="刷新">
          <el-button circle @click="refresh">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="导航设置">
          <el-button circle @click="showNavigationSettings">
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-tooltip>
        <el-dropdown @command="handleUserCommand">
          <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="content">
      <router-view v-slot="{ Component }">
        <transition name="fade-scale" mode="out-in">
          <component :is="Component" :key="$route.fullPath" />
        </transition>
      </router-view>
    </main>

    <!-- Launchpad触发按钮 -->
    <div class="launchpad-trigger" @click="toggleLaunchpad">
      <div class="trigger-button" :class="{ active: launchpadVisible }">
        <el-icon :size="32">
          <component :is="launchpadVisible ? 'Close' : 'Grid'" />
        </el-icon>
      </div>
    </div>

    <!-- Mac Launchpad导航 -->
    <transition name="launchpad-fade">
      <div v-if="launchpadVisible" class="launchpad-overlay" @click="closeLaunchpad">
        <div class="launchpad-container" @click.stop @wheel.prevent="handleWheel">
          <!-- 顶部搜索 -->
          <div class="launchpad-header">
            <el-input
              v-model="searchText"
              placeholder="搜索应用..."
              clearable
              size="large"
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button class="close-btn" circle @click="closeLaunchpad">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>

          <!-- 分页滚动容器 -->
          <div class="launchpad-scroll-container" ref="scrollContainerRef">
            <div 
              class="launchpad-pages-wrapper" 
              :style="{ transform: `translateX(-${currentPage * 100}%)` }"
            >
              <!-- 每一页 -->
              <div 
                v-for="page in totalPages" 
                :key="page"
                class="launchpad-page"
              >
                <div class="apps-grid">
                  <div
                    v-for="app in getAppsForPage(page)"
                    :key="app.path"
                    class="app-item"
                    @click="handleAppClick(app)"
                    @mouseenter="hoveredApp = app"
                    @mouseleave="hoveredApp = null"
                  >
                    <div class="app-icon-wrapper">
                      <div class="app-icon" :style="{ background: app.color }">
                        <el-icon :size="32">
                          <component :is="app.icon" />
                        </el-icon>
                      </div>
                      <div v-if="app.badge" class="app-badge">
                        {{ app.badge }}
                      </div>
                    </div>
                    <div class="app-title">{{ app.title }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 底部页面指示器 -->
          <div class="launchpad-footer">
            <div class="page-indicators">
              <div 
                v-for="page in totalPages"
                :key="page"
                class="page-indicator"
                :class="{ active: currentPage === page - 1 }"
                @click="goToPage(page - 1)"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 快捷功能面板 -->
    <div class="quick-actions">
      <el-tooltip content="命令面板 (Ctrl+K)" placement="left">
        <div class="quick-action-btn" @click="toggleCommandPanel">
          <el-icon :size="20"><Operation /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip content="回到首页" placement="left">
        <div class="quick-action-btn" @click="goHome">
          <el-icon :size="20"><HomeFilled /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip content="全屏" placement="left">
        <div class="quick-action-btn" @click="toggleFullscreen">
          <el-icon :size="20"><FullScreen /></el-icon>
        </div>
      </el-tooltip>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import { Grid, Close, Refresh, Operation, HomeFilled, FullScreen, Setting, Search } from '@element-plus/icons-vue'
import { menuData } from '@/config/menu'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const navigationStore = useNavigationStore()

const launchpadVisible = ref(false)
const searchText = ref('')
const currentPage = ref(0)
const appsPerPage = 20 // 每页20个应用
const hoveredApp = ref(null)
const scrollContainerRef = ref(null)

// 颜色配置
const menuConfig = {
  '/sales': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  '/inventory': 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  '/finance': 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  '/member': 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
  '/reports': 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  '/system': 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
  '/extensions': 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
  '/purchase': 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
  '/lowcode': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  '/contract': 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
  '/asset': 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  '/equipment': 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
  '/manufacturing': 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  '/hr': 'linear-gradient(135deg, #f77062 0%, #fe5196 100%)'
}

// 生成所有应用项（扁平化所有菜单项）
const allApps = computed(() => {
  const apps = []
  
  menuData.forEach(item => {
    // 添加主菜单项
    apps.push({
      path: item.path,
      title: item.title,
      icon: ElementPlusIconsVue[item.icon] || ElementPlusIconsVue['Document'],
      color: menuConfig[item.path] || 'linear-gradient(135deg, #6c757d 0%, #495057 100%)',
      badge: item.badge || '',
      category: item.path
    })
    
    // 添加子菜单项
    if (item.children && item.children.length > 0) {
      item.children.forEach(child => {
        apps.push({
          path: child.path,
          title: child.title,
          icon: ElementPlusIconsVue[child.icon] || ElementPlusIconsVue['Document'],
          color: menuConfig[item.path] || 'linear-gradient(135deg, #6c757d 0%, #495057 100%)',
          badge: child.badge || '',
          category: item.path,
          parent: item.title
        })
      })
    }
  })
  
  return apps
})

// 过滤后的应用
const filteredApps = computed(() => {
  if (!searchText.value) {
    return allApps.value
  }
  
  const keyword = searchText.value.toLowerCase()
  return allApps.value.filter(app =>
    app.title.toLowerCase().includes(keyword) ||
    app.path.toLowerCase().includes(keyword) ||
    (app.parent && app.parent.toLowerCase().includes(keyword))
  )
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredApps.value.length / appsPerPage) || 1
})

// 获取指定页的应用
const getAppsForPage = (page) => {
  const start = (page - 1) * appsPerPage
  const end = start + appsPerPage
  return filteredApps.value.slice(start, end)
}

// 切换Launchpad
const toggleLaunchpad = () => {
  launchpadVisible.value = !launchpadVisible.value
  if (launchpadVisible.value) {
    currentPage.value = 0
    searchText.value = ''
  }
}

// 关闭Launchpad
const closeLaunchpad = () => {
  launchpadVisible.value = false
}

// 处理应用点击
const handleAppClick = (app) => {
  router.push(app.path)
  closeLaunchpad()
  ElMessage.success(`打开 ${app.title}`)
}

// 切换到指定页
const goToPage = (page) => {
  currentPage.value = page
}

// 处理滚轮事件
const handleWheel = (event) => {
  if (event.deltaX !== 0 || Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
    // 水平滚动
    if (event.deltaX > 0 && currentPage.value < totalPages.value - 1) {
      // 向右滚动，下一页
      currentPage.value++
    } else if (event.deltaX < 0 && currentPage.value > 0) {
      // 向左滚动，上一页
      currentPage.value--
    }
  }
}

// 监听搜索变化，重置到第一页
watch(searchText, () => {
  currentPage.value = 0
})

// 监听页数变化
watch(totalPages, (newVal) => {
  if (currentPage.value >= newVal) {
    currentPage.value = Math.max(0, newVal - 1)
  }
})

const toggleCommandPanel = () => {
  navigationStore.toggleCommandPanel()
}

const goHome = () => {
  router.push('/dashboard')
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const refresh = () => {
  router.go(0)
}

const showNavigationSettings = () => {
  // 触发导航设置对话框
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  } else if (command === 'profile') {
    router.push('/system/user-settings')
  } else if (command === 'settings') {
    router.push('/system/settings')
  }
}
</script>

<style scoped>
.mac-launchpad-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
}

.header {
  height: 60px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 999;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  height: 36px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  height: 0;
  background: #f0f2f5;
  padding: 20px;
}

/* Launchpad触发按钮 */
.launchpad-trigger {
  position: fixed;
  bottom: 40px;
  right: 40px;
  z-index: 2000;
}

.trigger-button {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.trigger-button:hover {
  transform: scale(1.1) rotate(90deg);
  box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6);
}

.trigger-button.active {
  transform: rotate(135deg);
  background: linear-gradient(135deg, #f56c6c 0%, #f5576c 100%);
}

/* Mac Launchpad样式 */
.launchpad-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(20px);
  z-index: 1999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.launchpad-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部搜索栏 */
.launchpad-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 60px 20px;
  position: relative;
}

.search-input {
  width: 600px;
  max-width: 80vw;
}

.search-input :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.search-input :deep(.el-input__inner) {
  color: white;
}

.close-btn {
  position: absolute;
  right: 60px;
  top: 40px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 分页滚动容器 */
.launchpad-scroll-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.launchpad-pages-wrapper {
  display: flex;
  height: 100%;
  width: 100%;
  transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.launchpad-page {
  width: 100%;
  height: 100%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-y: auto;
  padding: 40px;
}

/* 应用网格 */
.apps-grid {
  display: grid;
  grid-template-columns: repeat(5, 140px);
  grid-template-rows: repeat(4, 140px);
  gap: 40px;
  max-width: 900px;
  width: 100%;
  padding: 20px 0;
}

.app-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 16px;
  border-radius: 16px;
}

.app-item:hover {
  transform: translateY(-8px) scale(1.05);
}

.app-icon-wrapper {
  position: relative;
}

.app-icon {
  width: 80px;
  height: 80px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.app-item:hover .app-icon {
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);
  transform: scale(1.1);
}

.app-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  padding: 4px 8px;
  background: linear-gradient(135deg, #f56c6c 0%, #ff6b9d 100%);
  color: white;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.app-title {
  font-size: 14px;
  color: white;
  text-align: center;
  font-weight: 500;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 底部页面指示器 */
.launchpad-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

.page-indicators {
  display: flex;
  gap: 12px;
  align-items: center;
}

.page-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-indicator:hover {
  background: rgba(255, 255, 255, 0.5);
  transform: scale(1.2);
}

.page-indicator.active {
  width: 24px;
  border-radius: 4px;
  background: white;
  box-shadow: 0 2px 8px rgba(255, 255, 255, 0.5);
}


/* 快捷操作 */
.quick-actions {
  position: fixed;
  right: 40px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 12px;
  z-index: 1000;
}

.quick-action-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.quick-action-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

/* 动画 */
.fade-scale-enter-active,
.fade-scale-leave-active {
  transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.fade-scale-enter-from {
  opacity: 0;
  transform: scale(0.8);
}

.fade-scale-leave-to {
  opacity: 0;
  transform: scale(1.2);
}

.launchpad-fade-enter-active,
.launchpad-fade-leave-active {
  transition: all 0.3s ease;
}

.launchpad-fade-enter-from,
.launchpad-fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .apps-grid {
    grid-template-columns: repeat(4, 120px);
    grid-template-rows: repeat(5, 120px);
    gap: 30px;
  }
  
  .app-icon {
    width: 70px;
    height: 70px;
  }
}

@media (max-width: 1024px) {
  .apps-grid {
    grid-template-columns: repeat(3, 100px);
    grid-template-rows: repeat(6, 100px);
    gap: 24px;
  }
  
  .app-icon {
    width: 60px;
    height: 60px;
  }
  
  .app-title {
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .apps-grid {
    grid-template-columns: repeat(2, 80px);
    grid-template-rows: repeat(9, 80px);
    gap: 20px;
  }
  
  .app-icon {
    width: 50px;
    height: 50px;
  }
  
  .launchpad-header {
    padding: 20px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .close-btn {
    right: 20px;
    top: 20px;
  }
}

/* 滚动条样式 */
.launchpad-page::-webkit-scrollbar {
  width: 8px;
}

.launchpad-page::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.launchpad-page::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.launchpad-page::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 键盘导航支持 */
.app-item:focus {
  outline: 2px solid white;
  outline-offset: 4px;
}

/* 加载动画优化 */
.launchpad-pages-wrapper {
  will-change: transform;
}
</style>


